package affd.logic;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

public class Utilities {
	
	public static final String DEFAULT_ENCODING = "UTF8";
	
	/**
	 * Creates a reader with specified encoding. If encoding is null the default
	 * encoding is used.
	 * 
	 * @param filename Filename to be read.
	 * @param encoding Encoding to be used.
	 * @return New reader.
	 * @throws IOException
	 */
	public static BufferedReader createReader(String filename, String encoding) throws IOException {
		// Set encoding
		if(encoding == null) {
			encoding = DEFAULT_ENCODING;
		}
		
		InputStreamReader inputStream = new InputStreamReader(new FileInputStream(filename), encoding);
		BufferedReader reader = new BufferedReader(inputStream);
		
		return reader;
	}
	
	/**
	 * Creates a writer with specified encoding. If encoding is null the default
	 * encoding is used.
	 * 
	 * @param filename Filename to be write.
	 * @param encoding Encoding to be used.
	 * @return New writer.
	 * @throws IOException
	 */
	public static BufferedWriter createWriter(String filename, String encoding) throws IOException {
		// Set encoding
		if(encoding == null) {
			encoding = DEFAULT_ENCODING;
		}
		
		OutputStreamWriter outputStream = new OutputStreamWriter(new FileOutputStream(filename), encoding);
		BufferedWriter writer = new BufferedWriter(outputStream);
		
		return writer;
	}
	
	/**
	 * Copies the file to the specified directory.
	 * 
	 * @param filename File to be copied.
	 * @param directory Output directory of the file.
	 * @throws IOException
	 */
	public static void copyFile(String filename, String directory) throws IOException {
		File source = new File(filename);
		File destination= new File(directory);
		
		// Create streams
		InputStream inputStream = new FileInputStream(source.getAbsolutePath());
		OutputStream outputStream = new FileOutputStream(destination.getAbsolutePath() + source.getName());
		
		// Transfer bytes from in to out 
		byte[] buffer = new byte[1024];
		int length;
		while ((length = inputStream.read(buffer)) > 0) {
			outputStream.write(buffer, 0, length);
		}
		
		// Close streams
		inputStream.close();
		outputStream.close();
	}
	
	/**
	 * Removes the specified file.
	 * 
	 * @param filename File to be removed.
	 */
	public static void deleteFile(String filename) {
		File file = new File(filename);
		
		// Delete file
		if(file.exists())
			file.delete();
	}

}
